package com.lhn.juc;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * CyclicBarrier demo
 *
 * @author lhn
 * @date 2022/09/21 21:11
 * @since 1.0.0
 **/
public class CyclicBarrierTest {

    @Test
    public void test() {

    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        final CyclicBarrier cyclic = new CyclicBarrier(3);
        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(() -> {
                System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    cyclic.await();//当前线程调用此方法，则计数减一
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("子线程" + Thread.currentThread().getName() + "执行完成");
            }, "Thread-1-" + i);
            service.execute(thread);
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 4; i++) {
            Thread thread = new Thread(() -> {
                System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    cyclic.await();//当前线程调用此方法，则计数减一
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("子线程" + Thread.currentThread().getName() + "执行完成");
            }, "Thread-2-" + i);
            service.execute(thread);
        }
        System.out.println("主线程"+Thread.currentThread().getName()+"等待子线程执行完成...");
        System.out.println("主线程"+Thread.currentThread().getName()+"开始执行...");
    }
}